package rfcomm;

import java.io.IOException;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

public class Server
{

    private UUID uuid;
    private String url;
    private StreamConnectionNotifier scnotifier;
    private StreamConnection sc;
    private Envelope envelope;
    private Status status;

    public Server(
        String urlString,
        Envelope envelope,
        Status status )
    {
        uuid = new UUID( urlString, false );
        url = "btspp://localhost:" + uuid.toString() + ";name=Server SSP";
        this.envelope = envelope;
        this.status = status;
    }

    /**
     * Connect and register a new device and its stream
     */
    public void connectAndRegisterRequest()
    {
        try {
            while( status.getStatus() ) {
                scnotifier = (StreamConnectionNotifier) Connector.open( url );
                sc = scnotifier.acceptAndOpen();
                
                envelope.setPaired( new PairNeighborConnection(
                    RemoteDevice.getRemoteDevice( sc ),
                    sc ) );
            }            
        } catch( IOException e ) {
            System.out.println( "Server: tentativa de abrir conexão mal sucedida" );
        }
    }
}